
from __future__ import division
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from joblib import dump, load
import keyboard

from pyod.models.iforest import IForest
from pyod.models.knn import KNN
from pyod.models.pca import PCA 
from pyod.utils.data import evaluate_print
from pyod.utils.example import visualize, data_visualize

if __name__ == "__main__":

    columns = ["t", "DtaNgx_1s", "DtaNgy_1s", "DtaNgz_1s"]

    # file_name = os.listdir("./examples/temp_data")

    data = pd.read_csv("./train_data/17.IMU控制消息 (3437) .dat", sep='\t', usecols=columns)

    # data = data.loc[data["t"] > 1630]
    data = data.loc[data["t"] < 1200]
    data = data.drop(labels="t", axis=1)

    print(data.head(5))

    data_len = data.shape[0]

    train_len = int(data_len * 0.6)
    test_len = int(data_len * 0.4)


    x_test = data.values[:test_len]
    x_train = data.values[test_len:]
    y_train = np.zeros(data_len - test_len,)
    y_test = np.zeros(test_len,)


    # fig = plt.figure(figsize=(10, 7))
    # ax = plt.axes(projection="3d")
    # # ax.scatter(data["DtaNgx_1s"][data_len - 10000:], data["DtaNgy_1s"][data_len - 10000:], data["DtaNgz_1s"][data_len - 10000:])
    # ax.scatter(data["DtaNgx_1s"], data["DtaNgy_1s"], data["DtaNgz_1s"])
    # plt.axis([-18000, 18000,-18000, 18000, -18000, 18000])
    # plt.show()


    # data_visualize(x_train, y_train, show_figure=True, save_figure=False)
    # print(x_train)
    # print(x_test)
    

    # train IForest detector
    # clf_name = 'IForest'
    # clf = IForest()
    # clf_name = 'KNN'
    # clf = KNN(contamination=0.00001)
    clf_name = "PCA"
    clf = PCA(contamination=0.00001, n_components=3)
    clf.fit(x_train)

    # get the prediction labels and outlier scores of the training data
    y_train_pred = clf.labels_  # binary labels (0: inliers, 1: outliers)
    y_train_scores = clf.decision_scores_  # raw outlier scores
    print(np.count_nonzero(y_train_pred))

    print(x_train[np.nonzero(y_train_pred)])
    # get the prediction on the test data
    y_test_pred = clf.predict(x_test)  # outlier labels (0 or 1)
    y_test_scores = clf.decision_function(x_test)  # outlier scores
    print(np.count_nonzero(y_test_pred))

    # evaluate and print the results
    # print("\nOn Training Data:")
    # evaluate_print(clf_name, y_train, y_train_scores)
    # print("\nOn Test Data:")
    # evaluate_print(clf_name, y_test, y_test_scores)

    # example of the feature importance
    # feature_importance = clf.feature_importances_
    # print("Feature importance", feature_importance)

    # visualize the results
    # visualize(clf_name, x_train[:,1:3], y_train, x_test[:,1:3], y_test, y_train_pred,
    #           y_test_pred, show_figure=True, save_figure=False)

    # save model to disk
    dump(clf, '../model_files/IMU_Gyro_Model.joblib')

    print("Model saved successfully.")

    keyboard.wait('esc')

